//
//  ViewController.m
//  IOS-4-guess
//
//  Created by RIOS on 2018/4/9.
//  Copyright © 2018年 RIOS. All rights reserved.
//

#import "ViewController.h"
#import "CZData.h"

@interface ViewController ()<UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UIButton *image;
@property (weak, nonatomic) IBOutlet UIButton *vScore;
- (IBAction)hintClick:(id)sender;

@property (nonatomic,strong) NSArray *qusetion;
@property (weak, nonatomic) IBOutlet UILabel *page;
@property (weak, nonatomic) IBOutlet UILabel *answer;
@property (weak,nonatomic) UIButton *back;

- (IBAction)btnBigImage:(id)sender;
- (IBAction)btnImage:(id)sender;

@property (nonatomic) int  index;
@property (weak, nonatomic) IBOutlet UIView *vAnswer;
@property (weak, nonatomic) IBOutlet UIView *vChooseFont;


- (IBAction)next:(id)sender;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
      self.page.text = @"1/8";
    
    self.index = -1;
    [self gotoNext];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)hintClick:(id)sender {
    for (int i= 0; i<self.vAnswer.subviews.count;i++) {
        UIButton *btn = self.vAnswer.subviews[i];
        CZData *data = self.qusetion[self.index];
        NSString *single = [data.answer substringWithRange:NSMakeRange(i, 1)];
        if (![single isEqualToString:btn.currentTitle]) {
            [self btnAnswer:btn];
            [btn setTitle:single forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            [self addSocre:-10];
            
            break;
        }
    }
}

-(NSArray *)qusetion{
    if (_qusetion==nil) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"data.plist" ofType:nil];
        NSArray *array = [NSArray arrayWithContentsOfFile:path];
        NSMutableArray *mArray = [NSMutableArray new];
        
        for (NSDictionary *dict in array) {
           CZData *model = [CZData buildWithDict:dict];
           [mArray addObject:model];
             NSLog(@"model:%@",model.answer);
        }
        _qusetion = mArray;
        
    }
   
    
    return _qusetion;
    
}


-(void) gotoNext{
    self.index++;
    
    if (self.index > 7) {
        self.index = 0;
    }
    
    self.page.text = [NSString stringWithFormat:@"%d/8",self.index +1];
    CZData *data = self.qusetion[self.index];
    self.answer.text = data.answer;
    
    [self.image setBackgroundImage:[UIImage imageNamed:data.image] forState:UIControlStateNormal];
   
    //////////////////////
    [self.vAnswer.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    int w = 35;
    int margin = 5;
    CGFloat len = data.answer.length;
    int left = (self.view.frame.size.width - w*len-margin*(len-1))/2;
    
    
    for (int i=0; i<len; i++) {
        UIButton *btn = [UIButton new];
        [self.vAnswer addSubview:btn];
        //到添加答案框
        btn.frame = CGRectMake(left + (w+margin)*i, 2.5, w, w);
        btn.backgroundColor = [UIColor whiteColor];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn.layer setCornerRadius:3];
        [btn.layer masksToBounds];
        [btn addTarget:self action:@selector(btnAnswer:) forControlEvents:UIControlEventTouchUpInside];
      }
    /////////////////////////
    //////////////////////
    [self.vChooseFont.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
     len = 7;
   
     left = (self.view.frame.size.width - w*len-margin*(len-1))/2;
     NSArray *marray = [self getArrayString];
    
    for (int i=0; i< 14; i++) {
        UIButton *btn = [UIButton new];
        btn.tag = i;
        //到添加选择框
        btn.frame = CGRectMake(left + (w+margin)*(i%(int)len), (w+margin)*(int)(i/(int)len), w, w);
        btn.backgroundColor = [UIColor whiteColor];
        
        [btn.layer setCornerRadius:3];
        [btn.layer masksToBounds];
        [btn setTitle:marray[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

        btn.titleLabel.font = [UIFont systemFontOfSize:15];
         [self.vChooseFont addSubview:btn];
        [btn addTarget:self action:@selector(chooseClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    /////////////////////////
    
}

-(void)btnAnswer:(UIButton *)anBtn{
    NSLog(@"tag:%d",(int)anBtn.tag);
    for (int i= 0; i<self.vChooseFont.subviews.count;i++) {
       UIButton *btn = self.vChooseFont.subviews[i];
        NSLog(@"subview:%@",btn.currentTitle);
    }
    
        self.vChooseFont.subviews[(int)anBtn.tag].hidden = false;
    [anBtn setTitle:nil forState:UIControlStateNormal];
}

-(void)chooseClick:(UIButton *)btn{
    for (int i=0; i<self.vAnswer.subviews.count; i++) {
        UIButton *anBtn = self.vAnswer.subviews[i];
        if (anBtn.currentTitle == nil) {
            [anBtn setTitle:btn.currentTitle forState:UIControlStateNormal];
            anBtn.tag = btn.tag;
            btn.hidden = true;
            break;
        }
    }
    
    [self checkAnswer];
}

-(void)checkAnswer{
    NSMutableString *answer = [NSMutableString new];
    for (int i= 0; i<self.vAnswer.subviews.count;i++) {
         UIButton *anBtn = self.vAnswer.subviews[i];
        if (anBtn.currentTitle!=nil) {
            [answer appendString:anBtn.currentTitle];
        }else{
            break;
        }
        
    }
   CZData *data = self.qusetion[self.index];
    if ([data.answer isEqualToString:answer]) {
        NSLog(@"答案正确");
        for (int i= 0; i<self.vAnswer.subviews.count;i++) {
            UIButton *anBtn = self.vAnswer.subviews[i];
            [anBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        }
        if (self.index==7) {
           [[[UIAlertView alloc] initWithTitle:@"提示" message:@"恭喜通关" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",@"重做",nil] show];
        }else{
            
            [self performSelector:@selector(gotoNext) withObject:nil afterDelay:1];
//           [self gotoNext];
        }
        [self addSocre:1000];
        
    }else{
        NSLog(@"答案错误");
    }
    
}

-(void)addSocre:(int)score{
    [self.vScore setTitle:[NSString stringWithFormat:@"%d",self.vScore.currentTitle.intValue+score] forState:UIControlStateNormal];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"alerView:%d",buttonIndex);
}



-(NSArray *) getArrayString{
    NSString *string = @"因为孩子小好久没和老婆一个屋子睡觉了因为晚上孩子闹老婆怕我休息不好所以一直分房睡昨天晚上突发奇想的起睡吧结果睡到后半夜老婆做梦梦到孩子要掉地上一把抓住结果我的弟弟锤子毛毛无一幸免全部中招这感觉一阵酸爽啊";
    NSMutableArray *marray = [NSMutableArray new];
     CZData *data = self.qusetion[self.index];
    NSString *currentAnswer = data.answer;
    for (int i=0; i<currentAnswer.length; i++) {
        [marray addObject:[currentAnswer substringWithRange:NSMakeRange(i, 1)]];
    }
    
    while (marray.count < 14) {
        int seed = arc4random_uniform((int)string.length);
        [marray addObject:[string substringWithRange:NSMakeRange(seed, 1)]];
    }
    
  
    NSMutableArray *result = [NSMutableArray new];

    while (marray.count >0) {
        int seed = arc4random_uniform((int)marray.count);
        [result addObject:marray[seed]];
        [marray removeObjectAtIndex:seed];
    }
    
    
    
   
    return result;
}

- (NSString *)stringByReplaceUnicode:(NSString *)unicodeString {
    NSMutableString *convertedString = [unicodeString mutableCopy];
    [convertedString replaceOccurrencesOfString:@"\\U" withString:@"\\u" options:0 range:NSMakeRange(0, convertedString.length)];
    CFStringRef transform = CFSTR("Any-Hex/Java");
    CFStringTransform((__bridge CFMutableStringRef)convertedString, NULL, transform, YES);
    return convertedString;
}


-(void)gotoBigImage{
    if (self.back==nil) {
        UIButton *back = [UIButton new];
        self.back = back;
        self.back.frame = self.view.frame;
        self.back.backgroundColor = [UIColor blackColor];
        self.back.alpha = 0.0;
        [self.back addTarget:self action:@selector(btnImage:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.view addSubview: self.back];
        
        [self.view bringSubviewToFront:self.image];
        [UIView animateWithDuration:1 animations:^{
              self.back.alpha = 0.6;
              self.image.frame = CGRectMake(0, 150, 375, 375);
        }];
        
    }else{
        [UIView animateWithDuration:1 animations:^{
            self.back.alpha = 0.0;
            self.image.frame = CGRectMake(105, 105, 160, 160);
        } completion:^(BOOL finished) {
            if (finished) {
                [self.back removeFromSuperview];
                self.back = nil;
            }
        }];
    }
    
    
}

- (IBAction)next:(id)sender {
    [self gotoNext];
}

- (IBAction)btnBigImage:(id)sender {
    [self gotoBigImage];
}

- (IBAction)btnImage:(id)sender {
      [self gotoBigImage];
}
@end
